package com.wangp.mywrite.coding;

/***
 * @author wangpeng
 * @since 2022-02-23  10:03
 */
public class Reverse {

    public String reverseOnlyLetters(String s) {
        char[] tmp = new char[s.length()];
        int count = 0;
        char[] res = s.toCharArray();
        for (char c : res) {
            if (isLetter(c)) {
                tmp[count++] = c;
            }
        }
        int index = -1;
        for (int i = tmp.length - 1; i >= 0; i--) {
            if (isLetter(tmp[i])) {
                index = i;
                break;
            }
        }
        if (index < 1) {
            return s;
        }
        int start = 0;
        int end = index;
        while (start < end) {
            char c = tmp[start];
            tmp[start] = tmp[end];
            tmp[end] = c;

            start++;
            end--;
        }
        index = 0;
        for (int i = 0; i < res.length; i++) {
            if (isLetter(res[i])) {
                res[i] = tmp[index++];
            }
        }
        return new String(res);
    }

    private boolean isLetter(char c) {
        return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
    }


    public String reverseOnlyLetters2(String s) {
        char[] res = s.toCharArray();
        int n = res.length - 1;
        int start = 0;
        int end = n;
        while (start < end) {
            while (start <= n && !isLetter(res[start])) {
                start++;
            }
            while (end >= 0 && !isLetter(res[end])) {
                end--;
            }
            if (start < end) {
                swap(res, start, end);
                start++;
                end--;
            }
        }
        return new String(res);
    }

    private void swap(char[] carr, int i, int j) {
        char c = carr[i];
        carr[i] = carr[j];
        carr[j] = c;
    }

    public static void main(String[] args) {
        System.out.println(new Reverse().reverseOnlyLetters2("7_28"));
    }

}
